
package com.atzly.community.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class StringUtil extends StringUtils {

  public static String capitalize(String paramString) {
    if ((paramString == null) || (paramString.length() <= 0)) {
      return paramString;
    }

    char c = paramString.charAt(0);
    if (Character.isUpperCase(c)) {
      return paramString;
    }

    char[] arrayOfChar = paramString.toCharArray();
    arrayOfChar[0] = Character.toUpperCase(arrayOfChar[0]);

    return new String(arrayOfChar);
  }

  public static String contact(String split, String... values) {
    if (values == null) {
      return StringUtils.EMPTY;
    }
    String targetValue = StringUtils.EMPTY;
    for (String value : values) {
      if (!StringUtils.isEmpty(value)) {
        targetValue = targetValue.concat(value).concat(split);
      }
    }
    // 不为空的时候，剪掉最后一根split
    if (!StringUtils.isEmpty(targetValue)) {
      targetValue = targetValue.substring(0, targetValue.length() - 1);
    }
    return targetValue;
  }

  public static boolean contains(String str, String... strArray) {
    if (str == null || strArray == null) {
      return false;
    }
    for (String mem : strArray) {
      if (str.equals(mem)) {
        return true;
      }
    }
    return false;
  }

  public static boolean containsIgnoreCase(String str, String... strArray) {
    if (str == null || strArray == null) {
      return false;
    }
    for (String mem : strArray) {
      if (str.equalsIgnoreCase(mem)) {
        return true;
      }
    }
    return false;
  }

  public static String dateFormat(Timestamp date, String pattern) {
    if (date == null) {
      return null;
    }
    String ret = new SimpleDateFormat(pattern).format(date);
    return ret;
  }

  public static String dateFormat(Timestamp date) {
    return dateFormat(date, "yyyy-MM-dd");
  }

  public static boolean isBlankChar(char paramChar) {
    return (paramChar == ' ') || (paramChar == '\t') || (paramChar == '\r') || (paramChar == '\n');
  }

  public static String join(Collection<?> c, String separator) {
    if (c == null) {
      return null;
    }

    StringBuilder sb = new StringBuilder();
    Iterator<?> it = c.iterator();
    while (it.hasNext()) {
      sb.append(it.next());

      if (!it.hasNext()) {
        continue;
      }

      sb.append(separator);
    }

    return sb.toString();
  }

  /**
   * Boolean.True: true, yes, on, t, y, 1, others are Boolean.False
   * @param value
   * @return
   */
  public static Boolean parseBoolean(String value) {
    if (value != null) {
      if (1 == value.length()) {
        final char c = value.charAt(0);
        if ('1' == c) {
          return Boolean.TRUE;
        } else if ('0' == c) {
          return Boolean.FALSE;
        }
      }
    }
    return BooleanUtils.toBoolean(value);
  }

  public static String repeat(String s, int count) {
    if (StringUtil.isEmpty(s)) {
      return s;
    }

    if (count < 0) {
      // TODO: 指定编码
      throw new RuntimeException("str.CAN_err_invalid_repeat_count");
    }

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < count; i++) {
      sb.append(s);
    }

    return sb.toString();
  }

  public static String strip(String paramString) {
    if (paramString == null) {
      return null;
    }
    int k = paramString.length();
    if (k <= 0) {
      return null;
    }

    int i;
    for (i = 0; i < k; i++) {
      if (!isBlankChar(paramString.charAt(i))) {
        break;
      }
    }

    int j;

    for (j = k; j > i; j--) {
      if (!isBlankChar(paramString.charAt(j - 1))) {
        break;
      }
    }
    if (i >= j) {
      return null;
    }
    if ((i == 0) && (j == paramString.length())) {
      return paramString;
    }

    return paramString.substring(i, j);
  }

  /**
   * 判断字符串是否为空(包含null与""," ")
   *
   * @param str
   * @return
   */
  public static boolean isEmptyIgnoreBlank(String str) {
    if (str == null || "".equals(str) || "".equals(str.trim())) {
      return true;
    }
    return false;
  }

  /**
   * 将模板文本中的{varName}形式的部分替换为varName对应的变量值
   *
   * @param tpl
   * @param vars
   * @return
   */
  public static String renderTemplate(String tpl, Object vars, boolean strict) {
    if (tpl == null || tpl.trim().length() == 0) {
      return "";
    }

    if (vars == null) {
      return tpl;
    }

    int pos = tpl.indexOf("#{");
    if (pos < 0) {
      return tpl;
    }

    StringBuilder sb = new StringBuilder();
    sb.append(tpl.substring(0, pos));
    while (pos >= 0) {
      int endPos = tpl.indexOf('}', pos);
      if (endPos < 0) {
        sb.append(tpl.substring(pos));
        break;
      }

      String varName = tpl.substring(pos + 2, endPos);

      if (ReflectUtils.hasProperty(vars, varName)) {
        Object value = null;
        try {
          value = ReflectUtils.getProperty(vars, varName);
        } catch (Exception e) {
          log.error("titog err",e);
        }
        if (value != null) {
          sb.append(value);
        }
      } else {
        if (strict) {
          throw new RuntimeException("lang.CAN_err_unknown_property:" + varName);
        }

        sb.append(tpl.substring(pos, endPos + 1));
      }
      pos = tpl.indexOf("#{", endPos + 1);
      if (pos < 0) {
        sb.append(tpl.substring(endPos + 1));
        break;
      } else {
        sb.append(tpl.substring(endPos + 1, pos));
      }
    }
    return sb.toString();
  }

  /**
   * 包含符号
   */
  private static final String CHINESE_REGEX = "[\u0391-\uFFE5]";
  /**
   * 不包含符号
   */
  private static final String CHINESE_REGEX2 = "[\u4e00-\u9fa5]";


  /**
   * 获取字符串长度(中文算两位)
   * @param str 字符串
   * @return 字符串长度
   */
  public static int strLength(String str) {
    int length = 0;
    if (StringUtils.isBlank(str)) {
      return length;
    }
    for (int index = 0, strLength = str.length(); index < strLength; index++) {
      length += str.substring(index, index + 1).matches(CHINESE_REGEX) ? 2 : 1;
    }
    return length;
  }
  


	public static int codePointCount(String str) {
		return null == str ? 0 : str.codePointCount(0, str.length());
	}

  /**
   * 截取字符串(中文两字符)
   * @param str 字符串
   * @param start 开始位置
   * @param length 截取长度
   * @return 截取结果
   */
  public static String subString(String str, int start, int length) {
    StringBuilder builder = new StringBuilder();
    int subLength = 0;
    for (int index = start, strLength = str.length(); index < strLength; index++) {
      String charStr = str.substring(index, index + 1);
      builder.append(charStr);
      subLength += charStr.matches(CHINESE_REGEX) ? 2 : 1;
      if (subLength > length) {
        break;
      }
    }
    return builder.toString();
  }


  /**
   * 正则验证电子邮件
   * @param email 待校验邮箱
   * @return 校验结果
   */
  public static boolean isEmail(String email) {
    if (isEmpty(email)) {
      return false;
    }
    email = email.toLowerCase();
    String str = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
    Pattern p = Pattern.compile(str);
    Matcher m = p.matcher(email);
    return m.matches();
  }


  /**
   * 正则验证电子邮件(含166，198，199，147开始手机号)
   * @param mobile 待校验手机号
   * @return 校验结果
   */
  public static boolean isMobile(String mobile) {
    if (isEmpty(mobile)) {
      return false;
    }
    String regex = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$";
    Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(mobile);
    return matcher.matches();
  }

}
